package com.linwen.javase.file;

import org.junit.Test;

import java.io.*;

/**
 * @author : linwen
 * @date : 下午11:05 2021/9/7
 */
public class IOTest {
    /*
    * 文件数据读到内存中
    * */
    @Test
    public void test1(){
        File file = new File("hello.txt");
        if(file.exists()){
            FileReader fileReader =null;
            try{
                fileReader = new FileReader(file);
                //逐个写入
                /*int read;
                while ((read = fileReader.read())!= -1){
                    System.out.print((char)read);
                }
                */
                //char数组，缓冲写入，提高效率
                char[] cbuff = new char[5];
                int len;
                while ((len = fileReader.read(cbuff)) != -1){
                    String str = new String(cbuff,0,len);
                    System.out.print(str);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try{
                    if(fileReader != null){
                        fileReader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 内存数据写出到文件中
     * */
    @Test
    public void test2() throws IOException {
        File file = new File("out.txt");
        //是否在文件末尾追加写入
        FileWriter fileWriter = new FileWriter(file,false);
        fileWriter.write("hello\n");
        fileWriter.write("world");
        fileWriter.close();

    }
}
